import { defineStore } from "pinia";
import { ref } from "vue";
import { SceneType } from "./sceneStore";
import { v4 as uuidv4 } from "uuid";
import { ItemType, type IItem } from "@/type/item";

interface PlacedFurniture {
  id: string; // 家具实例ID，唯一的UUID
  furnitureId: string; // 家里类型ID，如oak_table
  position: {
    x: number;
    y: number;
  };
  rotation: number; // 旋转角度
  sceneType: SceneType; // 场景类型
  itemData: IItem; // 家具数据
}

const FURNITURE_STORAGE_KEY = "xinglu-valley-furniture";

export const useFurnitureStore = defineStore("furniture", () => {
  const placedFurniture = ref<PlacedFurniture[]>([
    {
      id: uuidv4(),
      furnitureId: "oak_table",
      position: {
        x: 400,
        y: 400,
      },
      rotation: 90,
      sceneType: SceneType.FARM,
      itemData: {
        id: "oak_table", // 家具ID
        name: "橡木桌",
        description: "可以作为装饰品摆放",
        type: ItemType.FURNITURE,
        stackable: true,
        maxStack: 99,
        sellPrice: 50,
        buyPrice: 200,
        placeable: true,
        imageUrl: "/src/assets/images/tiles/furniture.png",
        sourceRect: {
          x: 0,
          y: 569,
          width: 32,
          height: 39,
          drawWidth: 32,
          drawHeight: 39,
          offsetX: 0,
          offsetY: 0,
        },
      },
    },
  ]); // 放置的家具

  // 初始化家具
  const initFurniture = () => {
    const saveFurniture = localStorage.getItem(FURNITURE_STORAGE_KEY);
    if (saveFurniture) {
      try {
        placedFurniture.value = JSON.parse(saveFurniture);
      } catch (error) {
        console.error("加载家具数据失败：", error);
        placedFurniture.value = [];
      }
    }
  };

  // 保存家具
  const saveFurniture = () => {
    localStorage.setItem(
      FURNITURE_STORAGE_KEY,
      JSON.stringify(placedFurniture.value)
    );
  };

  /**
   * 添加家具
   * @param furnitureId 家具ID
   * @param position 放置位置
   * @param rotation 旋转角度
   * @param sceneType 场景类型
   */
  const addFurniture = (
    furnitureId: string,
    position: { x: number; y: number },
    rotation: number,
    sceneType: SceneType,
    itemData: IItem
  ) => {
    const id = uuidv4();
    const newFurniture: PlacedFurniture = {
      id,
      furnitureId,
      position,
      rotation,
      sceneType,
      itemData,
    };
    placedFurniture.value.push(newFurniture);
    saveFurniture();
    return id;
  };

  return {
    placedFurniture,
    initFurniture,
    addFurniture,
  };
});
